package com.nbcio.modules.erp.report.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nbcio.common.core.domain.R;
import com.nbcio.modules.erp.inventory.domain.ErpInvBalance;
import com.nbcio.modules.erp.inventory.domain.ErpInvLedger;
import com.nbcio.modules.erp.inventory.mapper.ErpInvBalanceMapper;
import com.nbcio.modules.erp.inventory.mapper.ErpInvLedgerMapper;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 库存报表控制器
 */
@RestController
@RequestMapping("/erp/report/inventory")
public class ErpInventoryReportController {

    @Resource
    private ErpInvBalanceMapper balanceMapper;
    @Resource
    private ErpInvLedgerMapper ledgerMapper;

    /**
     * 当前库存查询（分页）
     */
    @GetMapping("/balance/page")
    public R<Page<ErpInvBalance>> pageBalance(
            @RequestParam(required = false) String warehouseId,
            @RequestParam(required = false) String materialId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<ErpInvBalance> qw = new LambdaQueryWrapper<>();
        if (warehouseId != null && !warehouseId.isEmpty()) {
            qw.eq(ErpInvBalance::getWarehouseId, Long.parseLong(warehouseId));
        }
        if (materialId != null && !materialId.isEmpty()) {
            qw.eq(ErpInvBalance::getMaterialId, Long.parseLong(materialId));
        }
        // 只查询有库存的（数量大于0）
        qw.gt(ErpInvBalance::getQtyOnHand, BigDecimal.ZERO);
        qw.orderByDesc(ErpInvBalance::getUpdateTime);
        
        Page<ErpInvBalance> page = new Page<>(pageNum, pageSize);
        return R.ok(balanceMapper.selectPage(page, qw));
    }

    /**
     * 出入库明细查询（分页）
     */
    @GetMapping("/ledger/page")
    public R<Page<ErpInvLedger>> pageLedger(
            @RequestParam(required = false) String warehouseId,
            @RequestParam(required = false) String materialId,
            @RequestParam(required = false) String billType,
            @RequestParam(required = false) String ioType,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<ErpInvLedger> qw = new LambdaQueryWrapper<>();
        if (warehouseId != null && !warehouseId.isEmpty()) {
            qw.eq(ErpInvLedger::getWarehouseId, Long.parseLong(warehouseId));
        }
        if (materialId != null && !materialId.isEmpty()) {
            qw.eq(ErpInvLedger::getMaterialId, Long.parseLong(materialId));
        }
        if (billType != null && !billType.isEmpty()) {
            qw.eq(ErpInvLedger::getBillType, billType);
        }
        if (ioType != null && !ioType.isEmpty()) {
            qw.eq(ErpInvLedger::getIoType, ioType);
        }
        if (startTime != null && !startTime.isEmpty() && endTime != null && !endTime.isEmpty()) {
            qw.between(ErpInvLedger::getBizTime, startTime, endTime);
        }
        qw.orderByDesc(ErpInvLedger::getBizTime);
        
        Page<ErpInvLedger> page = new Page<>(pageNum, pageSize);
        return R.ok(ledgerMapper.selectPage(page, qw));
    }

    /**
     * 库存汇总统计
     */
    @GetMapping("/balance/summary")
    public R<Map<String, Object>> balanceSummary(
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(required = false) Long materialId) {
        LambdaQueryWrapper<ErpInvBalance> qw = new LambdaQueryWrapper<>();
        if (warehouseId != null) {
            qw.eq(ErpInvBalance::getWarehouseId, warehouseId);
        }
        if (materialId != null) {
            qw.eq(ErpInvBalance::getMaterialId, materialId);
        }
        
        List<ErpInvBalance> list = balanceMapper.selectList(qw);
        
        BigDecimal totalQty = list.stream()
                .map(ErpInvBalance::getQtyOnHand)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal totalAmount = list.stream()
                .map(ErpInvBalance::getAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        Map<String, Object> result = new HashMap<>();
        result.put("totalQty", totalQty);
        result.put("totalAmount", totalAmount);
        result.put("itemCount", list.size());
        return R.ok(result);
    }
}

